
from .context_free_grammar import *


def grammar_from_lines(lines: list) -> ContextFreeGrammar:
    start_symbol = lines[0].strip()
    n = len(lines)
    assert is_regular_nonterminal(
        start_symbol), 'start symbol is not regular'
    cfg = ContextFreeGrammar(start_state=start_symbol)
    for i in range(1, n):
        line = lines[i].strip()
        nt, prods_str = line.split(' -> ')

        prods_list = prods_str.split('|')
        for index, item in enumerate(prods_list):
            item = item.strip()
            prods_list[index] = Production(item)
        entry = Entry(nt, prods_list)
        cfg.add_entry(entry)

    assert cfg.is_well_formed()
    return cfg

def regular_grammar_stdin():
    lines = []
    while True:
        try:
            s = input()
            lines.append(s)
        except:
            break
    return grammar_from_lines(lines)

def regular_grammar_input(filename: str):
    with open(filename, 'r') as f:
        lines = f.readlines()
        return grammar_from_lines(lines)
